package com.yupi.yupicturebackend.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.yupi.yupicturebackend.annotation.AuthCheck;
import com.yupi.yupicturebackend.common.BaseResponse;
import com.yupi.yupicturebackend.common.DeleteRequest;
import com.yupi.yupicturebackend.common.ResultUtils;
import com.yupi.yupicturebackend.exception.BusinessException;
import com.yupi.yupicturebackend.exception.ErrorCode;
import com.yupi.yupicturebackend.exception.ThrowUtils;
import com.yupi.yupicturebackend.manager.CosManager;
import com.yupi.yupicturebackend.model.dto.space.*;
import com.yupi.yupicturebackend.model.entity.Space;
import com.yupi.yupicturebackend.model.entity.User;
import com.yupi.yupicturebackend.model.enums.SpaceLevelEnum;
import com.yupi.yupicturebackend.model.vo.SpaceVO;
import com.yupi.yupicturebackend.service.PictureService;
import com.yupi.yupicturebackend.service.SpaceService;
import com.yupi.yupicturebackend.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.time.Duration;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/space")
public class SpaceController {



    @Resource
    private UserService userService;


    @Resource
    private SpaceService spaceService;


    @Resource
    private PictureService pictureService;




    //添加空间
    @PostMapping("/add")
    public BaseResponse<Long> addSpace(@RequestBody SpaceAddRequest spaceAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(spaceAddRequest == null, ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        long newId = spaceService.addSpace(spaceAddRequest, loginUser);
        return ResultUtils.success(newId);
    }



    //删除图片
    @PostMapping("/delete")
    public BaseResponse<Boolean> deletespace(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if(deleteRequest==null||deleteRequest.getId()<=0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser( request);
        long id=deleteRequest.getId();
        Space oldspace = spaceService.getById(id);
        ThrowUtils.throwIf(oldspace==null,ErrorCode.NOT_FOUND_ERROR);

        if(!oldspace.getUserId().equals(loginUser.getId())&&!userService.isAdmin(loginUser)){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = spaceService.removeById(id);
        ThrowUtils.throwIf(!b,ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    @PostMapping("/update")
//    @AuthCheck(mustRole = "admin")
    public BaseResponse<Boolean> updatespace(@RequestBody SpaceUpdateRequest spaceUpdateRequest, HttpServletRequest request) {
        if(spaceUpdateRequest==null||spaceUpdateRequest.getId()<=0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        Space space=new Space();
        BeanUtil.copyProperties(spaceUpdateRequest,space);



        spaceService.validSpace( space,false);

        long id=spaceUpdateRequest.getId();
        Space oldspace = spaceService.getById(id);
        ThrowUtils.throwIf(oldspace==null,ErrorCode.NOT_FOUND_ERROR);


        boolean b = spaceService.updateById(space);
        ThrowUtils.throwIf(!b,ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);

    }

    //编辑图片
    @PostMapping("/edit")
    public BaseResponse<Boolean> editspace(@RequestBody SpaceEditRequest spaceEditRequest, HttpServletRequest request) {
        if(spaceEditRequest==null||spaceEditRequest.getId()<=0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser( request);

        //在此处将DTO进行转换
        Space space=new Space();
        BeanUtil.copyProperties(spaceEditRequest,space);
        //数据校验
        spaceService.validSpace( space,false);
        space.setEditTime(new Date());

        //判断是否存在
        long id=spaceEditRequest.getId();
        Space oldSpace = spaceService.getById(id);
        ThrowUtils.throwIf(oldSpace==null,ErrorCode.NOT_FOUND_ERROR);
        //仅限本人或者管理员可以编辑图片
        spaceService.checkSpaceAuth(loginUser, oldSpace);


        boolean b = spaceService.updateById(space);
        ThrowUtils.throwIf(!b,ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);




    }

    /**
     * 根据 id 获取图片（仅管理员可用）
     */
    @GetMapping("/get")
//    @AuthCheck(mustRole = "admin")
    public BaseResponse<Space> getspaceById(long id, HttpServletRequest request) {

        ThrowUtils.throwIf(id<=0,ErrorCode.PARAMS_ERROR);
        Space space = spaceService.getById(id);
        ThrowUtils.throwIf(space==null,ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(space);
    }

    /**
     * 根据 id 获取空间（封装类）
     */

    @GetMapping("/get/vo")
    public BaseResponse<SpaceVO> getspaceVOById(long id, HttpServletRequest request) {

        ThrowUtils.throwIf(id<=0,ErrorCode.PARAMS_ERROR);
        Space space = spaceService.getById(id);
        ThrowUtils.throwIf(space==null,ErrorCode.NOT_FOUND_ERROR);
        SpaceVO spaceVO = spaceService.getSpaceVO(space, request);
        User loginUser = userService.getLoginUser(request);

        //空间权限校验
        Long spaceId= space.getId();
        if(spaceId!=null){

            spaceService.checkSpaceAuth(loginUser,space);
        }

//        //  权限
//        if (!space.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
//            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
//        }
//        List< String> permissionList = spaceService.getPermissionList(space, loginUser);
//        spaceVO.setPermissionList(permissionList);

//        Long spaceId=space.getId();
//        if(spaceId!=null){
//
//            pictureService.checkSpaceAuth(loginUser, p);
//        }

        return ResultUtils.success(spaceVO);

    }


    /**
     * 分页获取图片列表（仅管理员可用）
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = "admin")
    public BaseResponse<Page<Space>> listspaceByPage(@RequestBody SpaceQueryRequest spaceQueryRequest) {

        ThrowUtils.throwIf(spaceQueryRequest==null,ErrorCode.PARAMS_ERROR);
        long current = spaceQueryRequest.getCurrent();
        long size = spaceQueryRequest.getPageSize();

        Page<Space> spacePage= spaceService.page(new Page<>(current, size),
                spaceService.getQueryWrapper(spaceQueryRequest)
                );

        return ResultUtils.success(spacePage);

    }

    @PostMapping("/list/page/vo")
    public BaseResponse<Page<SpaceVO>> listspaceVOByPage(@RequestBody SpaceQueryRequest spaceQueryRequest,
                                                            HttpServletRequest request) {

//
//        ThrowUtils.throwIf(spaceQueryRequest==null,ErrorCode.PARAMS_ERROR);
//
//        long current = spaceQueryRequest.getCurrent();
//        long size = spaceQueryRequest.getPageSize();
//        Page<Space> spacePage= spaceService.page(new Page<>(current, size),
//                spaceService.getQueryWrapper(spaceQueryRequest));
//        return ResultUtils.success(spaceService.getspaceVOPage(spacePage,request));

        long current = spaceQueryRequest.getCurrent();
        long size = spaceQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<Space> spacePage = spaceService.page(new Page<>(current, size),
                spaceService.getQueryWrapper(spaceQueryRequest));
        // 获取封装类
        return ResultUtils.success(spaceService.getspaceVOPage(spacePage, request));
    }

    //获取空间级别列表，便于前端展示
    @GetMapping("/list/level")
    public BaseResponse<List<SpaceLevel>> listSpaceLevel(){
        List<SpaceLevel>spaceLevelList=Arrays.stream(SpaceLevelEnum.values())
                .map(spaceLevelEnum -> new SpaceLevel(
                        spaceLevelEnum.getValue(),
                        spaceLevelEnum.getText(),
                        spaceLevelEnum.getMaxCount(),
                        spaceLevelEnum.getMaxSize()))
                .collect(Collectors.toList());
                return ResultUtils.success(spaceLevelList);
    }

}
